//
//  Floating.m
//  Floating Window
//
//  Created by 吴浪 on 15/8/24.
//  Copyright (c) 2015年 浪遥. All rights reserved.
//

#import "Floating.h"
#import "UIView+Frame.h"

#define FLOATWH 50.0 //默认宽高
#define kScreenWidth [[UIScreen mainScreen] bounds].size.width
#define kScreenHeight [[UIScreen mainScreen] bounds].size.height

@interface Floating ()
/**
 *  背景
 */
@property (nonatomic, weak) UIImageView *bgView;
/**
 *  遮盖View
 */
@property (nonatomic, weak) UIView *coverView;
@end

@implementation Floating

- (instancetype)init {
    
    if (self = [self initWithFrame:CGRectMake(kScreenWidth - FLOATWH, kScreenHeight - FLOATWH * 2, FLOATWH, FLOATWH)]) {
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initUI];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame imageName:(NSString *)imageName delegate:(id)delegate;{
    if (self = [self initWithFrame:frame]) {
        self.imageName = imageName;
        self.floatingDelegate = delegate;
    }
    return self;
}

+ (instancetype)floatingWithFrame:(CGRect)frame imageName:(NSString *)imageName delegate:(id)delegate;{
    return [[self alloc] initWithFrame:frame imageName:imageName delegate:delegate];
}


#pragma mark - 初始化视图
- (void)initUI {
    UIViewController *bgVC = [[UIViewController alloc] init];
    bgVC.view.frame = CGRectZero;
    self.rootViewController = bgVC;
    self.backgroundColor = [UIColor clearColor];
    self.windowLevel = UIWindowLevelAlert;
    [self makeKeyAndVisible];
    self.dragEnable = YES;
    self.contentViewTouchType = FloatingTouchTypeOneClick;
    //处理拖拽事件
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(locationChange:)];
    //    pan.delaysTouchesBegan = YES;
    [self addGestureRecognizer:pan];
    
    //处理点击事件
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(Oneclick:)];
    singleTap.numberOfTapsRequired = 1;
    [self addGestureRecognizer:singleTap];
    UITapGestureRecognizer *douleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(Twoclick:)];
    douleTap.numberOfTapsRequired = 2;
    [self addGestureRecognizer:douleTap];
    [singleTap requireGestureRecognizerToFail:douleTap];
    
    //处理长按事件
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressclick:)];
    [self addGestureRecognizer:longPress];
}

#pragma mark - 拖拽响应
- (void)locationChange:(UIGestureRecognizer *)gesture {
    if (!self.isDragEnable) {
        return;
    }
    CGPoint panPoint = [gesture locationInView:[UIApplication sharedApplication].keyWindow];
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(changeColor) object:nil];//取消先前的延迟事件
            self.bgView.alpha = 0.8;
            break;
        case UIGestureRecognizerStateEnded:
            [self setupFloatingViewWith:panPoint];
            break;
        case UIGestureRecognizerStateChanged:
            self.center = CGPointMake(panPoint.x, panPoint.y);
            break;
            
        default:
            break;
    }
    
};

#pragma mark - 处理悬浮窗的位置
- (void)setupFloatingViewWith:(CGPoint)startPoint {
    CGFloat endX = startPoint.x;
    CGFloat endY = startPoint.y;
    
    //处理不合理数据x
    if (endX <= kScreenWidth * 0.5) {
        endX = self.width * 0.5;
        endY = endY;
    }else {
        endX = kScreenWidth - self.width * 0.5;
        endY = endY;
    }
    
    //处理不合理数据y
    if (endY <= 20 + self.height * 0.5) {
        endX = endX;
        endY = 20 + self.height * 0.5;
    }
    if (endY >= kScreenHeight - self.height * 0.5) {
        endY = kScreenHeight - self.height * 0.5;
    }
    
    [UIView animateWithDuration:0.2f delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.center = CGPointMake(endX, endY);
    } completion:^(BOOL finished) {
        [self performSelector:@selector(changeColor) withObject:nil afterDelay:4.0f];
    }];
}

#pragma mark - 点击响应
- (void)Oneclick:(UIGestureRecognizer *)gesture {
    [self clickWithType:FloatingTouchTypeOneClick];
}
- (void)Twoclick:(UIGestureRecognizer *)gesture {
    [self clickWithType:FloatingTouchTypeTwoClick];
}
- (void)clickWithType:(FloatingTouchType)type {
    self.bgView.alpha = 0.8;
    if (self.contentViewTouchType == type && self.contentView != nil) {
        [self addCoverView];
    }
    
    [self performSelector:@selector(changeColor) withObject:nil afterDelay:4.0f];
    if ([self.floatingDelegate respondsToSelector:@selector(floatingDidClick:type:)]) {
        [self.floatingDelegate floatingDidClick:self type:type];
    }
}

#pragma mark - 添加内容视图
- (void)addCoverView {
    self.hidden = YES;
    if (self.coverView == nil) {
        UIView *coverView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        coverView.alpha = 0.0;
        coverView.backgroundColor = [UIColor clearColor];
        self.contentView.center = coverView.center;
        [coverView addSubview:self.contentView];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(disCoverView)];
        [coverView addGestureRecognizer:tap];
        [[UIApplication sharedApplication].keyWindow addSubview:coverView];
        [UIView animateWithDuration:0.5 animations:^{
            coverView.alpha = 1.0;
        } completion:^(BOOL finished) {
            self.coverView = coverView;
        }];
    }
}

- (void)disCoverView {
    [self.coverView removeFromSuperview];
    self.hidden = NO;
}

#pragma mark - 长按事件
- (void)longPressclick:(UIGestureRecognizer *)gesture {
    gesture.state == UIGestureRecognizerStateBegan ? [self clickWithType:FloatingTouchTypeLongPress] : nil; //长按手势会在 开始与结束 分别调用一次
}

#pragma mark - 颜色改变
-(void)changeColor
{
    [UIView animateWithDuration:2.0 animations:^{
        self.bgView.alpha = 0.2;
    }];
}

- (void)setImageName:(NSString *)imageName {
    _imageName = imageName;
    if (!self.bgView) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        imageView.image = [UIImage imageNamed:_imageName];
        imageView.alpha = 0.2;
        [self addSubview:imageView];
        self.bgView = imageView;
    }else {
        self.bgView.image = [UIImage imageNamed:_imageName];
    }
}


/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */
@end
